<?php

namespace app\api\controller;

use app\api\service\Token;
use app\BaseController;
use think\facade\Db;
use think\facade\Cache;

class Base extends BaseController
{
    protected $uid;
    protected $role;
    protected $token;
    // 无需 Token 验证的路由配置
    const EXCEPT_ROUTES = [
        'article' => ['index', 'read', 'myCollect'],
        'comment' => ['list', 'index'],
        'account' => ['info'],
        'follow'  => ['index', 'list'],
        'pay' => ['notifyUrl', 'returnUrl']
    ];

    public function __construct()
    {
        // 检查系统是否关闭
        if (getConfig('admin', 'sys_main')['app_switch'] == 0) {
            json_msg('App正在升级，请稍后再来尝试');
        }

        // 初始化用户信息
        $this->init();
    }

    /**
     * 初始化用户信息
     */
    protected function init()
    {
        $token = request()->header('token') ?? input('token');
        $this->token = $token;
        $requiresToken = $this->requiresTokenValidation();
        if ($requiresToken) {
            $this->validateToken($token);
        } elseif (!empty($token)) {
            $this->loadUserFromToken($token);
        }
    }

    /**
     * 验证 Token 并加载用户信息
     *
     * @param string $token
     */
    protected function validateToken($token)
    {
        if (empty($token)) {
            json_msg('请登录后再来操作哦！', '', 210);
        }

        $userData = $this->getUserFromCache($token);
        if (!$userData) {
            json_msg('请登录后再来操作哦！', '', 210);
        }
        (new Token)->autoExpireTime($token);
        $this->uid = $userData['id'];
    }

    /**
     * 从 Token 加载用户信息
     *
     * @param string $token
     */
    protected function loadUserFromToken($token)
    {
        $userData = $this->getUserFromCache($token);
        if ($userData) {
            $this->uid = $userData['id'];
            $this->token = $token;
            $this->checkStatus();
        }
    }

    /**
     * 从缓存中获取用户信息
     *
     * @param string $token
     * @return array|null
     */
    protected function getUserFromCache($token)
    {
        $userData = Cache::get($token);
        return $userData ? json_decode($userData, true) : null;
    }

    /**
     * 检查用户状态
     */
    protected function checkStatus()
    {
        $user = Db::name('user')
            ->where('id', $this->uid)
            ->find();

        if (!$user) {
            json_msg('用户不存在');
        }

        if ($user['status'] == 0) {
            json_msg('用户待审核');
        }

        if ($user['status'] == 2) {
            json_msg('账户已被封禁');
        }
    }

    /**
     * 判断当前路由是否需要 Token 验证
     *
     * @return bool
     */
    protected function requiresTokenValidation()
    {
        $controller = strtolower(request()->controller());
        $action = request()->action();
        // 如果路由在白名单中，则无需 Token 验证
        if (isset(self::EXCEPT_ROUTES[$controller]) && in_array($action, self::EXCEPT_ROUTES[$controller])) {
            return false;
        }

        return true;
    }
}
